package main

import (
	"flag"
	"fmt"
	"gitee.com/shijun123456/kcgin"
	"gitee.com/shijun123456/rpcVotes/internal/config"
	"gitee.com/shijun123456/rpcVotes/internal/routes"
	"gitee.com/shijun123456/rpcVotes/internal/svc"
	"gitee.com/shijun123456/srpcinterface/client/utils"
	"github.com/tal-tech/go-zero/core/logx"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/tal-tech/go-zero/core/conf"
)

func kcginInit() {
	fmt.Printf("Enviroment: %s\n", kcgin.KcConfig.RunMode)
}

//服务注册
func register(client *utils.ConsulClient) {
	err := client.ServiceRegisterByMicro()
	if err != nil {
		log.Printf("err:%s", err.Error())
	}
}
func unregister(client *utils.ConsulClient) {
	client.ServiceUnRegisterByMicro()
}
func loginit() {
	logxFlag, _ := kcgin.AppConfig.Bool("isLog")
	if !logxFlag {
		logx.Disable()
	}
}

var client *utils.ConsulClient = utils.DefaultConsulClient()

var configFile = flag.String("f", "etc/votes.yaml", "the config file")

func main() {
	defer func() {
		if err := recover(); err != nil {
			unregister(client)
		}
	}()

	kcginInit()
	loginit()
	flag.Parse()
	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGALRM, os.Interrupt, syscall.SIGKILL)
	s := routes.RegisterRoutes(c, ctx)
	defer s.Stop()

	go register(client)
	go func() {
		<-ch
		unregister(client)
		os.Exit(1)
	}()
	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
